<?php

namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page; 

class SpecialController extends BaseController {
	function _initialize() {
		parent::_initialize ();
	}

	public function index() {
		$msg=M("wx_salelist");

		$keyword=I('keyword');
	    $saleid=I('saleid');
        $where="1=1";
        
        if($saleid){
        	$where.=" and a.saleid='$saleid'";
        }
        
		if($keyword)
		{
		   $where.=" and c.salename  like '%".$keyword."%' or a.goodsname like '%".$keyword."%' or a.price like '%".$keyword."%' or a.unit like '%".$keyword."%'";
		} 
		
		$where= str_replace("1=1 and", "", $where);
		$where= str_replace("1=1", "", $where);
		
	    $count =$msg->alias("a")->join(" left join ".$this->dbprefix."wx_sale c on a.saleid=c.saleid")->join(" left join ".$this->dbprefix."admin_user b on a.operationuser=b.user_id")->where($where)->count(); // 查询满足要求的总记录数

		$Page = new Page ($count, 12 ); // 实例化分页类 传入总记录数和每页显示的记录数
		$Page -> setConfig('header', '条记录');
		$Page -> setConfig('theme', '<li><a>%totalRow% %header%</a></li> <li>%upPage%</li> <li>%downPage%</li> <li>%first%</li>  <li>%prePage%</li>  <li>%linkPage%</li>  <li>%nextPage%</li> <li>%end%</li> ');//(对thinkphp自带分页的格式进行自定义)
		$show = $Page->show (); // 分页显示输出

		$ret=$msg->alias("a")->field("a.*,c.salename,c.isactive,b.user_name as adminname")->join(" left join ".$this->dbprefix."wx_sale c on a.saleid=c.saleid")->join(" left join ".$this->dbprefix."admin_user b on a.operationuser=b.user_id")->where($where)->limit( $Page->firstRow . ',' . $Page->listRows )->order("a.createtime desc")->select(); 

		$sort=M("wx_sale")->field("saleid,salename")->select();
		
		$this->assign ( "sort", $sort ); 
		$this->assign ( "sale", $ret );
		$this->assign ( "page", $show ); // 赋值分页输出 
		$this->display ();
	}
	
	//有个传递特价主题编号，一个是没有传主题编号
	public function add()
	{
		$id=I("saleid");		
		$id= isset($id)?$id:'';
		$id =empty($id)?'':$id; 
		
		$op=I("op");
		$op =empty($op)?'add':$op;
		
		$sort=M("wx_sale")->field("saleid,salename")->select(); 
		$this->assign ( "sort", $sort ); 
		
		if($id){
		  $ls=M("wx_salelist")->alias("a")->field("a.*,c.salename")->join(" left join ".$this->dbprefix."wx_sale c on a.saleid=c.saleid")->where("a.saleid='$id'")->order("a.createtime desc")->select();
		}
		
		$this->assign ("ls",$ls);
		$this->assign ("sid",$id); 
		$this->display ();
	}
 
   
	public function addsale() { 
		
		$ret=array('staute'=>'error','msg'=>"保存失败");
		$sid=I("sid");
		$postdata=I("json");
		
		if(empty($sid)||empty($postdata)){
			$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
		} 
		
		$json = json_decode($postdata,true); 
		if(!is_array($json)){
			$ret=array('staute'=>'error','msg'=>"特价商品信息错误");
			$this->ajaxReturn ($ret);
			exit;
		}
		
		//对数据进行处理
		 $sl=M("wx_salelist");
		 $dblist= $sl->where("saleid='$sid'")->select(); //数据库当前主题存在的记录信息;
		 
		 $aryadd=$arydel=$aryupd=array();
		 
		 //提交数据 是否在数据库中存在，存在更新否则增加
		 foreach($json as $k=>$v){ 
		 	$flg=0;
		 	foreach ($dblist as $key=>$o){ 
		 	  if($v["saleid"]==$o['saleid'] && $v["listid"]==$o['listid'] && $v["goodsid"]==$o['goodsid']){
		 	  	  $aryupd[]=$v;		
		 	  	  $flg=1;
		 	  	  break;
		 	  }
		 	}
		   if($flg==0){
		   	    $v["saleid"]=$sid;
		     	$aryadd[]=$v;
		   }
		 }
		 
		 //在数据库里存在，但是提交的数据不存在，删除数据
		 foreach ($dblist as $key=>$o){
		 	$bl=0;
		 	foreach($json as $k=>$v){
		 	  if($v["saleid"]==$o['saleid'] && $v["listid"]==$o['listid'] && $v["goodsid"]==$o['goodsid']){ 
		 			$bl=1;
		 			break;
		 		}
		 	}
		 	if($bl==0){
		 		$arydel[]=$o;
		 	}
		 }
		  
		 $sqladd=$sqlupd=$sqldel="";
		 $arysqlupd=array();  
		 $time=date("Y-m-d H:i:s");
		 
		 //构建插入数据语句
		 if(count($aryadd)>0){
		 	$sqlval=""; 
		 	foreach ($aryadd as $k=>$v){
		 		$listid=getGuid();//创建guid值
		 		$sqlval.=((empty($sqlval)?"":",")."('$listid','$sid','".$v['goodsid']."','".$v['goodsname']."','".$v['price']."','".$v['unit']."',".UID.",'$time')");
		 	}
		 	$sqladd=" INSERT INTO  ".$this->dbprefix."wx_salelist(`listid`,`saleid`,`goodsid`,`goodsname`,`price`,`unit`,`operationuser`,`createtime`) values ".$sqlval;
		 }
		 
		 //构建更新数据语句
		 if(count($aryupd)>0){  
		 	foreach ($aryupd as $k=>$v){
		 		$sqlupd="update ".$this->dbprefix."wx_salelist set saleid='$sid',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',price='".$v['price']."',unit='".$v['unit']."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
		 		$arysqlupd[]=$sqlupd;
		 	} 
		 }
		
		 //构建删除数据语句
		 if(count($arydel)>0){
		 	$sqlval="";
		 	foreach ($arydel as $k=>$v){
		 		$sqlval.=((empty($sqlval)?"":",").$v['listid']);
		 	}
		 	if(!empty($sqlval))
		 	   $sqldel="delete ".$this->dbprefix."wx_salelist where FIND_IN_SET(listid,'".$sqlval."')";
		 }
		 
		 $db=M("wx_salelist");
		 $retadd=$retupd= $retdel=1; //默认是成功状态
		 
		 $db->startTrans(); //启动事务
		 
		 if($sqladd){
		    $retadd=$db->execute($sqladd);
		 } 
		 
		 if(count($arysqlupd)>0){
			 foreach ($arysqlupd as $k=>$sql){
			 	if(empty($sql))continue;
			    $retupd=$db->execute($sql);
			    //如果失败就退出循环，失败
			    if(!$retupd){
			    	break;  
			    }
			 }
		 }
		 
		 if($sqldel){
		    $retdel=$db->execute($sqldel);
		 }
		 
		 if($retadd && $retupd && $retdel){
		    $db->commit();
		    $ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		    $db->rollback();
		    $ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }  
		$this->ajaxReturn($ret);
		
	}

	public function delsale(){
		$id=I("id");
		if(empty($id)){
			$this->error("传递参数错误!");
		} 
		$where="FIND_IN_SET(listid,'$id')";
		$result = M("wx_salelist")->where($where)->delete();
		if ($result) {
			$this->success("删除成功!");
		}
		else{
			$this->error ( "删除失败！" );
		}
	}

	/*
	public function getbyid(){
		$result = M("wx_reply")->where(array("id"=>$_POST["id"]))->find();
		if ($result) {
			$this->ajaxReturn($result);
		}
	} 
	*/

}
?>
